package com.jt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/consumer/doRestEcho01")
    public String doRestEcho01(){
        String url="http://localhost:8081/provider/echo/8090";
        return restTemplate.getForObject(url, String.class);
    }
//    @Autowired
//    private LoadBalancerClient loadBalancerClient;
//
//    @Value("${spring.application.name:8090}")
//    private String appName;
//
//    @GetMapping("/consumer/doRestEcho02")
//    public String doRestEcho02(){
//        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
//        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
//        System.out.println("request url:"+url);
//        return restTemplate.getForObject(url, String.class);
//    }
    @Autowired
    //借助此对象，从nacos获取服务实例，基于负载均衡算法进行远端服务调用
    private LoadBalancerClient loadBalancerClient;
    @Value("${spring.application.name:8090}")
    private String appName;
    @GetMapping("/consumer/doRestEcho02")
    public String doRestEcho02(){
        //基于服务名获取服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        //基于服务实例构建要访问的服务的URL
        String url = String.format("http://%s:%s/provider/echo/%s", serviceInstance.getHost(),serviceInstance.getPort(),appName);
        System.out.println("request url:"+url);
        return restTemplate.getForObject(url, String.class);

    }
    @Autowired
//    @Qualifier("loadBalancedRestTemplate")
//    private RestTemplate restTemplate2;
    private RestTemplate loadBalancedRestTemplate;
    @GetMapping("/consumer/doRestEcho03")
    public String doRestEcho03(){
        String url=String.format("http://%s/provider/echo/%s","sca-provider",appName);
//        String url=String.format("http://%s/provider/echo/{msg}","sca-provider");
        //向服务提供方发起http请求,获取响应数据
        return loadBalancedRestTemplate.getForObject(
                url,//要请求的服务的地址
                String.class);//String.class为请求服务的响应结果类型
//        return loadBalancedRestTemplate.getForObject(
//                url,//要请求的服务的地址
//                String.class,appName);//String.class为请求服务的响应结果类型
    }

}

